<!-- 保障成员添加/修改 -->
<template>
  <a-modal
    :visible="visible"
    :title="`${$isEmpty(data) ? '添加' : '修改'}保障成员`"
    :okText="$isEmpty(data) ? '添加' : '修改'"
    :confirmLoading="isSubmit"
    :afterClose="handleClose"
    width="80%"
    @ok="handleSubmit"
    @cancel="handleCancel"
  >
    <a-spin :spinning="spinning">
      <a-form :label-col="{ span: 10 }" :wrapper-col="{ span: 14 }" :form="form">
        <div>
          <div class="text-center fz-16">
            <a-icon type="user" :style="{ fontSize: '16px' }" />
            <span class="m-l-10">个人基本信息</span>
          </div>
          <a-divider></a-divider>
        </div>
        <a-row :gutter="16" type="flex">
          <a-col :span="6">
            <a-form-item label="姓名">
              <a-input
                placeholder="请输入姓名"
                v-decorator="['Name', { rules: [{ required: true, message: '请输入姓名' }] }]"
                @blur="getMarriageResult"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="联系电话">
              <a-input
                placeholder="请输入联系电话"
                v-decorator="['Phones', { rules: [{ required: true, validator: validatorPhone }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="身份证号" hasFeedback :help="idCardHelp">
              <a-input
                placeholder="请输入身份证号"
                v-decorator="['IDCards', { rules: [{ required: true, validator: validatorIDCard }] }]"
                @blur="getMarriageResult"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="性别">
              <a-select
                placeholder="请选择性别"
                v-decorator="['Sexs', { rules: [{ required: true, message: '请选择性别' }] }]"
              >
                <a-select-option value="男">男</a-select-option>
                <a-select-option value="女">女</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="出生日期">
              <a-date-picker
                placeholder="请选择出生日期"
                valueFormat="YYYY-MM-DD"
                v-decorator="['Birthdays', { rules: [{ required: true, message: '请选择出生日期' }] }]"
              >
              </a-date-picker>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="民族">
              <a-select
                show-search
                placeholder="请选择民族"
                v-decorator="['Nations', { rules: [{ required: true, message: '请选择民族' }] }]"
                optionFilterProp="label"
              >
                <a-select-option
                  v-for="item in nationOptions"
                  :key="item.DROPKEY"
                  :value="item.DROPKEY"
                  :label="item.DROPVALUE"
                  >{{ item.DROPVALUE }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="关系">
              <a-select
                placeholder="请选择关系"
                v-decorator="['Relation', { rules: [{ required: true, message: '请选择关系' }] }]"
                @change="handleChange('Relation', $event)"
              >
                <a-select-option v-for="item in relationOptions" :key="item.DROPKEY" :value="item.DROPKEY">{{
                  item.DROPVALUE
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="文化程度">
              <a-select
                placeholder="请选择文化程度"
                v-decorator="['College', { rules: [{ required: true, message: '请选择文化程度' }] }]"
              >
                <a-select-option v-for="item in collegeOptions" :key="item.DROPKEY" :value="item.DROPKEY">{{
                  item.DROPVALUE
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="婚姻状况">
              <a-select
                placeholder="请选择婚姻状况"
                v-decorator="['Maritalstas', { rules: [{ required: true, message: '请选择婚姻状况' }] }]"
              >
                <a-select-option
                  v-for="item in marriageOptions"
                  :key="item.DROPKEY"
                  :value="item.DROPVALUE"
                  :disabled="form.getFieldValue('Relation') === 42 && item.DROPVALUE !== '已婚'"
                  >{{ item.DROPVALUE }}</a-select-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="就业情况">
              <a-select
                placeholder="请选择就业情况"
                v-decorator="['Employment', { rules: [{ required: true, message: '请选择就业情况' }] }]"
                @change="handleChange('Employment', $event)"
              >
                <a-select-option v-for="item in employmentOptions" :key="item.DROPKEY" :value="item.DROPVALUE">{{
                  item.DROPVALUE
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="工作单位">
              <a-input
                placeholder="请输入工作单位"
                :disabled="form.getFieldValue('Employment') !== '在职'"
                v-decorator="[
                  'WorkUnits',
                  { rules: [{ required: form.getFieldValue('Employment') === '在职', message: '请输入工作单位' }] },
                ]"
              >
              </a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="职业">
              <a-select
                placeholder="请选择职业"
                v-decorator="['Profession', { rules: [{ required: true, message: '请选择职业' }] }]"
              >
                <a-select-option v-for="item in professionOptions" :key="item.DROPKEY" :value="item.DROPKEY">{{
                  item.DROPVALUE
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="居住地址">
              <a-cascader
                :options="options"
                :allowClear="false"
                placeholder="请选择居住地址"
                v-decorator="[
                  'LiveDistrictAddressArr',
                  {
                    initialValue: ['贵州省', '贵阳市'],
                    rules: [{ required: true, message: '请选择居住地址' }, { validator: validatorDistrictAddress }],
                  },
                ]"
              >
              </a-cascader>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="详细地址">
              <a-textarea
                placeholder="请输入详细地址"
                v-decorator="['LiveAddresss', { rules: [{ required: true, message: '请输入详细地址' }] }]"
                :auto-size="{ minRows: 1, maxRows: 2 }"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="是否残疾">
              <a-select
                placeholder="请选择是否残疾"
                v-decorator="['IfDisabilitys', { rules: [{ required: true, message: '请选择是否残疾' }] }]"
              >
                <a-select-option value="是">是</a-select-option>
                <a-select-option value="否">否</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6" v-show="form.getFieldValue('IfDisabilitys') === '是'">
            <a-form-item label="残疾类别">
              <a-select
                placeholder="请选择残疾类别"
                v-decorator="[
                  'DisabilityTypes',
                  {
                    initialValue: '',
                    rules: [{ required: form.getFieldValue('IfDisabilitys') === '是', message: '请选择残疾类别' }],
                  },
                ]"
              >
                <a-select-option v-for="item in disabilityTypeOptions" :key="item.DROPKEY" :value="item.DROPKEY">{{
                  item.DROPVALUE
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6" v-show="form.getFieldValue('IfDisabilitys') === '是'">
            <a-form-item label="残疾等级">
              <a-select
                placeholder="请选择残疾等级"
                v-decorator="[
                  'DisabilityLevels',
                  {
                    initialValue: '',
                    rules: [{ required: form.getFieldValue('IfDisabilitys') === '是', message: '请选择残疾等级' }],
                  },
                ]"
              >
                <a-select-option v-for="item in disabilityLevelOptions" :key="item.DROPKEY" :value="item.DROPKEY">{{
                  item.DROPVALUE
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <div>
          <div class="text-center fz-16">
            <a-icon type="team" />
            <span class="m-l-10">户籍及其相关信息</span>
          </div>
          <a-divider></a-divider>
        </div>
        <a-row type="flex">
          <a-col :span="6">
            <a-form-item label="申请人所属群体">
              <a-select
                mode="multiple"
                v-decorator="['GroupOfApplicants', { rules: [{ required: true, message: '请选择申请人所属群体' }] }]"
              >
                <a-select-option v-for="item in groupsOptions" :key="item.DROPKEY" :value="item.DROPKEY">{{
                  item.DROPVALUE
                }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="收入认定">
              <a-input
                disabled
                v-decorator="['IfLowObjects', { rules: [{ required: true, message: '请输入收入认定' }] }]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6" v-show="ifLowObjects === '低保'">
            <a-form-item label="低保证号">
              <a-input
                v-decorator="[
                  // 'LowObjectNOs',
                  // { initialValue: '', rules: [{ required: ifLowObjects === '低保', message: '请输入低保证号' }] },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="户籍信息">
              <a-select
                v-decorator="['ApplyTypes', { rules: [{ required: true, message: '请选择户籍信息' }] }]"
                @change="handleChange('ApplyTypes', $event)"
              >
                <a-select-option value="本市">本市</a-select-option>
                <a-select-option value="非本市">非本市</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6" v-show="form.getFieldValue('ApplyTypes') === '非本市'">
            <a-form-item label="居住证号">
              <a-input
                v-decorator="[
                  'IfRangeLowObject',
                  {
                    initialValue: '',
                    rules: [{ required: form.getFieldValue('ApplyTypes') === '非本市', message: '请输入居住证号' }],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="6" v-show="form.getFieldValue('ApplyTypes') === '非本市'">
            <a-form-item label="社保证号或完税证明">
              <a-input
                v-decorator="[
                  'SecurityNos',
                  {
                    initialValue: '',
                    rules: [
                      { required: form.getFieldValue('ApplyTypes') === '非本市', message: '请输入社保证号或完税证明' },
                    ],
                  },
                ]"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="6">
            <a-form-item label="户籍地址">
              <a-cascader
                v-if="form.getFieldValue('ApplyTypes') === '本市'"
                :options="options"
                :allowClear="false"
                placeholder="请选择户籍地址"
                v-decorator="[
                  'censusRegister',
                  {
                    initialValue: ['贵州省', '贵阳市'],
                    rules: [{ required: true, message: '请选择户籍地址' }, { validator: validatorDistrictAddress }],
                  },
                ]"
              >
              </a-cascader>
              <area-cascader
                v-else
                placeholder="请选择户籍地址"
                v-decorator="[
                  'censusRegister',
                  { initialValue: [], rules: [{ required: true, message: '请选择户籍地址' }] },
                ]"
              ></area-cascader>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="详细地址">
              <a-textarea
                placeholder="请输入详细地址"
                v-decorator="['CensusRegAddresss', { rules: [{ required: true, message: '请输入详细地址' }] }]"
                :auto-size="{ minRows: 1, maxRows: 2 }"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
  </a-modal>
</template>

<script>
import { getDropdownList } from '@/api/common'
import { areaCascader } from '@/components'
import { IDCardAble, getMarriage } from '@/api/communityReviewManagement'
import { validIDCard, validTelphone } from '@/utils/validate'
import moment from 'moment'
import lodash from 'lodash'
export default {
  inject: ['hasIDCard', 'applicationPerson'],
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    data: {
      type: Object,
      default: () => {},
    },
    ifLowObjects: {
      type: String,
      default: '无',
    },
    hasAapplicant: {
      type: Boolean,
      default: false,
    },
    isapplicant: {
      type: Boolean,
      default: false,
    },
  },
  watch: {
    visible(n) {
      if (n) {
        this.spinning = true
        this.fetchData()
      }
    },
  },
  components: {
    areaCascader,
  },
  data() {
    return {
      spinning: false,
      selectApplicant: false,
      nationOptions: [],
      relationOptions: [],
      collegeOptions: [],
      marriageOptions: [],
      employmentOptions: [],
      professionOptions: [],
      disabilityTypeOptions: [],
      disabilityLevelOptions: [],
      groupsOptions: [],
      options: [
        {
          value: '贵州省',
          label: '贵州省',
          disabled: true,
          children: [
            {
              value: '贵阳市',
              label: '贵阳市',
              disabled: true,
              children: [
                {
                  value: '南明区',
                  label: '南明区',
                },
                {
                  value: '云岩区',
                  label: '云岩区',
                },
                {
                  value: '乌当区',
                  label: '乌当区',
                },
                {
                  value: '白云区',
                  label: '白云区',
                },
                {
                  value: '观山湖区',
                  label: '观山湖区',
                },
                {
                  value: '开阳县',
                  label: '开阳县',
                },
                {
                  value: '息烽县',
                  label: '息烽县',
                },
                {
                  value: '修文县',
                  label: '修文县',
                },
                {
                  value: '清镇市',
                  label: '清镇市',
                },
              ],
            },
          ],
        },
      ],
      isSubmit: false,
      form: this.$form.createForm(this, { name: 'assure' }),
      idCardHelp: '',
    }
  },
  methods: {
    fetchData() {
      const getNation = getDropdownList({ PmKey: 'Nation' })
      const getRelation = getDropdownList({ PmKey: 'Relation' })
      const getCollege = getDropdownList({ PmKey: 'College' })
      const getMarriageOptions = getDropdownList({ PmKey: 'Marriage' })
      const getEmployment = getDropdownList({ PmKey: 'Employment' })
      const getProfession = getDropdownList({ PmKey: 'Profession' })
      const getDisabilityType = getDropdownList({ PmKey: 'DisabilityType' })
      const getDisabilityLevel = getDropdownList({ PmKey: 'DisabilityLevel' })
      const getGroups = getDropdownList({ PmKey: 'Groups' })
      Promise.all([
        getNation,
        getRelation,
        getCollege,
        getMarriageOptions,
        getEmployment,
        getProfession,
        getDisabilityType,
        getDisabilityLevel,
        getGroups,
      ])
        .then((res) => {
          this.nationOptions = res[0]
          if (!this.$isEmpty(this.data)) {
            this.relationOptions = res[1]
            if (this.isapplicant) {
              this.relationOptions.unshift({
                DROPKEY: 0,
                DROPVALUE: '申请人',
                disabled: true,
              })
            } else {
              this.relationOptions.unshift({
                DROPKEY: 0,
                DROPVALUE: '申请人',
              })
            }
          } else if (this.hasAapplicant) {
            this.relationOptions = res[1]
            if (this.isapplicant) {
              this.relationOptions.unshift({
                DROPKEY: 0,
                DROPVALUE: '申请人',
                disabled: true,
              })
            } else {
              this.relationOptions.unshift({
                DROPKEY: 0,
                DROPVALUE: '申请人',
              })
            }
          } else {
            this.relationOptions = res[1]
            if (this.isapplicant) {
              this.relationOptions.unshift({
                DROPKEY: 0,
                DROPVALUE: '申请人',
                disabled: true,
              })
            } else {
              this.relationOptions.unshift({
                DROPKEY: 0,
                DROPVALUE: '申请人',
              })
            }
          }
          // if (!this.$isEmpty(this.data)) {
          //   if (this.data.Relation !== 0) {
          //     this.relationOptions = res[1]
          //   } else {
          //     this.relationOptions = [
          //       {
          //         DROPKEY: 0,
          //         DROPVALUE: '申请人',
          //       },
          //     ]
          //   }
          // } else if (this.hasAapplicant) {
          //   this.relationOptions = res[1]
          // } else {
          //   this.relationOptions = [
          //     {
          //       DROPKEY: 0,
          //       DROPVALUE: '申请人',
          //     },
          //   ]
          // }
          this.collegeOptions = res[2]
          this.marriageOptions = res[3]
          this.employmentOptions = res[4]
          this.professionOptions = res[5]
          this.disabilityTypeOptions = res[6]
          this.disabilityLevelOptions = res[7]
          this.groupsOptions = res[8]

          if (!this.$isEmpty(this.data)) {
            const data = lodash.omit(lodash.cloneDeep(this.data), [
              'ID',
              'LID',
              'ApplyNO',
              'RelationName',
              'ProvinceAddress',
              'CityAddress',
              'DistrictAddress',
              'LiveDistrictAddress',
              'SpecialCareTypes',
              'IfPerHousProperties',
              'PersonHouse',
              'LeaseHouse',
              'HouseArea',
              'Mode',
            ])
            data.Birthdays = moment(data.Birthdays).format('YYYY-MM-DD')
            data.LiveDistrictAddressArr = ['贵州省', '贵阳市', this.data.LiveDistrictAddress]
            if (!Array.isArray(data.GroupOfApplicants)) {
              data.GroupOfApplicants = data.GroupOfApplicants.split(',').map((e) => Number(e))
            }
            this.form.setFieldsValue(data)
            this.$nextTick(() => {
              const censusRegister = [this.data.ProvinceAddress, this.data.CityAddress, this.data.DistrictAddress]
              // 添加延时
              setTimeout(() => {
                this.form.setFieldsValue({
                  censusRegister: censusRegister,
                })
              }, 50)
            })
          }
          this.form.setFieldsValue({
            IfLowObjects: '无',
          })
          // 添加家庭成员 默认填写申请人居住地址等信息
          if (this.hasAapplicant && this.$isEmpty(this.data)) {
            const applicationPerson = this.applicationPerson()
            this.form.setFieldsValue({
              LiveDistrictAddressArr: ['贵州省', '贵阳市', applicationPerson.LiveDistrictAddress],
              LiveAddresss: applicationPerson.LiveAddresss,
              ApplyTypes: applicationPerson.ApplyTypes,
              CensusRegAddresss: applicationPerson.CensusRegAddresss,
            })
            this.$nextTick(() => {
              const censusRegister = [
                applicationPerson.ProvinceAddress,
                applicationPerson.CityAddress,
                applicationPerson.DistrictAddress,
              ]
              // 添加延时
              setTimeout(() => {
                this.form.setFieldsValue({
                  censusRegister: censusRegister,
                })
              }, 50)
            })
          }
        })
        .finally(() => {
          this.spinning = false
        })
    },
    validatorPhone(rule, value, callback) {
      if (this.$isEmpty(value)) {
        callback(new Error('请输入联系电话'))
        return
      }
      if (!validTelphone(value)) {
        callback(new Error('不是有效的手机号码'))
      } else {
        callback()
      }
    },
    validatorDistrictAddress(rule, value, callback) {
      if (value.length !== 3) {
        callback(new Error('请选择居住地址'))
      } else {
        callback()
      }
    },
    validatorIDCard(rule, value, callback) {
      if (this.$isEmpty(value)) {
        callback(new Error('请输入身份证号'))
        this.idCardHelp = '请输入身份证号'
        return
      }
      if (!validIDCard(value)) {
        callback(new Error('不是有效的身份证号码'))
        this.idCardHelp = '不是有效的身份证号码'
      } else {
        this.idCardHelp = '正在查询身份证是否可用...'
        if (this.hasIDCard(value) && this.data.IDCards !== value) {
          this.idCardHelp = '此身份证已添加,请重新输入'
          callback(new Error('此身份证已添加保障成员,请重新输入'))
          return
        }
        IDCardAble({ idcard: value, ID: this.data.ID }).then((res) => {
          const state = res[0].state
          if (state === '0') {
            const sexNumber = value.charAt(16)
            const birthday = value.substring(6, 10) + '-' + value.substring(10, 12) + '-' + value.substring(12, 14)
            this.form.setFieldsValue({
              Sexs: sexNumber % 2 === 0 ? '女' : '男',
              Birthdays: moment(birthday).format('YYYY-MM-DD'),
            })
            this.idCardHelp = ''
            callback()
          } else {
            if (!this.$isEmpty(this.data) && value === this.data.IDCards) {
              this.idCardHelp = ''
              callback()
              return
            }
            this.idCardHelp = res[0].msg || '身份证不可用,请重新输入'
            callback(new Error('身份证不可用,请重新输入'))
          }
        })
      }
    },
    handleChange(key, e) {
      switch (key) {
        case 'ApplyTypes':
          this.form.setFieldsValue({
            censusRegister: e === '本市' ? ['贵州省', '贵阳市'] : [],
            IfRangeLowObject: '',
            SecurityNos: '',
          })
          break
        case 'Employment':
          this.form.setFieldsValue({
            WorkUnits: e === '在职' ? '' : '无',
          })
          break
        case 'Relation':
          if (this.data.Relation == 0 && e != 0) {
            this.selectApplicant = false
          } else if (e == 0) {
            this.selectApplicant = true
          } else {
            this.selectApplicant = this.isapplicant
          }
          const Maritalstas = this.form.getFieldValue('Maritalstas')
          if (e === 42 && Maritalstas !== '已婚') {
            this.form.setFieldsValue({
              Maritalstas: '已婚',
            })
          } else {
            this.form.setFieldsValue({
              Maritalstas: undefined,
            })
          }
          break
        default:
          break
      }
    },
    getMarriageResult() {
      if (process.env.NODE_ENV === 'development') return
      const values = this.form.getFieldsValue(['Name', 'IDCards'])
      const { Name, IDCards: idcard } = values
      if (!this.$isEmpty(Name) && validIDCard(idcard)) {
        this.$loading.show({
          tip: '查询婚姻状况中...',
        })
        getMarriage({
          Name,
          idcard,
        })
          .then((res) => {
            const { state, msg } = res[0]
            if (state === '1') {
              if (this.marriageOptions.some((e) => e.DROPVALUE === msg)) {
                this.form.setFieldsValue({
                  Maritalstas: msg,
                })
              } else {
                this.$message.error('婚姻状况绑定失败，请自行选择')
              }
            } else {
              this.$message.error('婚姻状况查询失败,请重试')
            }
          })
          .finally(() => {
            this.$loading.hide()
          })
      }
    },
    handleClose() {
      this.$emit('update:visible', false)
      this.$emit('update:data', {})
      this.form.resetFields()
      // this.$nextTick(() => {
      //   this.form.setFieldsValue({
      //     censusRegister: ['贵州省', '贵阳市']
      //   })
      // })
    },
    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          const { Relation, censusRegister, LiveDistrictAddressArr } = values
          const data = Object.assign({}, values, {
            ID: this.data.ID || '',
            LID: this.data.LID || '',
            ApplyNO: this.data.ApplyNO || '',
            RelationName: this.relationOptions.find((e) => e.DROPKEY === Relation).DROPVALUE,
            ProvinceAddress: censusRegister[0],
            CityAddress: censusRegister[1],
            DistrictAddress: censusRegister[2],
            LiveDistrictAddress: LiveDistrictAddressArr[2],
            SpecialCareTypes: this.data.SpecialCareTypes || '',
            IfPerHousProperties: this.data.IfPerHousProperties || '',
            PersonHouse: this.data.PersonHouse || '',
            LeaseHouse: this.data.LeaseHouse || '',
            HouseArea: this.data.HouseArea || '',
            Mode: this.data.Mode || '',
            IfLowObjects: this.data.IfLowObjects || '无',
          })
          this.$emit('change', {
            type: this.$isEmpty(this.data) ? 'add' : 'edit',
            selectApplicant: this.selectApplicant,
            data,
          })
          this.handleClose()
        }
      })
    },
    handleCancel() {
      this.handleClose()
    },
  },
}
</script>
<style lang="less" scoped>
.ant-calendar-picker {
  width: 100%;
}
</style>
